package com.iot08.api.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iot08.common.entity.app.IotCardInfo;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.RandomUtil;
import com.iot08.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @Description:
 * @author: Rock
 * @time: 2021/1/12 16:00
 */
@Slf4j
@Service
public class IotCardInfoService extends BaseService<IotCardInfo> {


    /**
     * 更新物联网卡通讯录信息
     *
     * @param iotCardInfo
     * @param moblies
     * @time: 2023/12/22 18:36
     * @author: Weichao
     * @version 1.0
     */
    public void updareContacts(IotCardInfo iotCardInfo, JSONArray moblies) {
        if (moblies != null && !moblies.isEmpty()) {
            Map<String, Map<String, Object>> newContactMap = new HashMap<>();
            //以传入的为准
            for (int i = 0; i < moblies.size(); i++) {
                JSONObject item = moblies.getJSONObject(i);
                String phone = item.getString("phone");
                Map<String, Object> temp = new HashMap<>();
                if(iotCardInfo.getContactMap().containsKey(phone)){
                    //用原有的 t 和 nick
                    Map<String, Object> oldItem = iotCardInfo.getContactMap().get(phone);
                    temp.put("name", oldItem.get("name"));
                    temp.put("t", oldItem.get("t"));
                }else{
                    int index = phone.length()-4;
                    index = (index < 0) ? 0 : index;
                    temp.put("name", "白名单"+phone.substring(index));
                    temp.put("t", DateUtil.nowTimestampToLong());
                }
                temp.put("phone", phone);

                newContactMap.put(phone,temp);
            }
            iotCardInfo.setContactMap(newContactMap);
            //更新操作
            this.save(iotCardInfo);
        }
    }

}
